<template>
  <ws-wx-privacy id="privacy-popup" page="2"></ws-wx-privacy>
  <uni-popup id="runse" type="center" ref="runse" :isMaskClick="false">
    <view class="runse-popup">
      <view class="runse-popup__header">
        <view class="ws-picker__title">
          <image :src="runseIcon" style="width:16px;height:16px;"></image>
          AI润色
        </view>
      </view>
      <scroll-view style="max-height:600rpx;font-size:28rpx;" :scroll-y="true">{{ AIendText }}
        <uv-loading-icon mode="semicircle" v-if="ailoading" customStyle="justify-content: left"></uv-loading-icon>
      </scroll-view>
      <view class="next uni-row" style="margin:60rpx 0 0 0;">
        <view style="flex:1;margin-right:10rpx">
          <uv-button type="primary" text="取消" plain @click="stopRunse"></uv-button>
        </view>
        <view style="flex:1;">
          <uv-button type="primary" text="确认润色" @click="doAi"></uv-button>
        </view>
      </view>
    </view>
  </uni-popup>
  <view>
    <view style="padding:20rpx 30rpx;margin-top:30rpx;background: #fff">
      <view class="postForm">
        <view class="item uni-row">
          <view class="title">选择领导：</view>
          <view class="lable">{{ postparms.leaderName }}</view>
        </view>
        <view class="item uni-row">
          <view class="title">留言类别：</view>
          <view class="lable">{{ postparms.type }}</view>
        </view>
        <view class="item uni-row">
          <view class="title">留言领域：</view>
          <view class="lable">{{ postparms.classify }}</view>
        </view>
      </view>
    </view>
    <view class="form">
      <view class="form-item uni-row" style="border-bottom: 1px solid #ddd;padding-bottom: 20rpx;width:100%">
        <view class="lable">* 标题：</view>
        <input placeholder="请输入标题,最多22个字" v-model="postData.title" maxlength="22" style="flex:1"
               placeholder-style="color:#c0c4cc"></input>
      </view>
      <view class="form-item" style="margin-top:30rpx;position: relative">
        <view class="lable">* 正文：</view>
        <uv-textarea :placeholder="contentplaceholder" border="bottom" v-model="postData.content" :height="160"
                     :customStyle="{padding:'0 0 70rpx 0',margin:'0'}"
                     :textStyle="{color:'#000',fontSize:'30rpx','line-height':'40rpx'}"
                     maxlength="-1"></uv-textarea>
        <view class="Aitext" @click="goAitext">
          <image :src="runseIcon" style="width:16px;height:16px;"></image>
          使用AI润色
        </view>
      </view>
      <view class="form-item" style="margin-top:40rpx;">
        <uv-upload :fileList="fileList1" multiple :maxCount="9" @afterRead="afterRead" width="100" height="100" accept="image"
                   uploadText="上传图片"
                   @delete="deletePic"></uv-upload>
      </view>
      <view class="form-item" style="padding-top:20rpx;border-top: 0.5px solid #dadbde;">
        <view class="lable" style="padding-bottom:20rpx;">视频：</view>
        <uv-upload :fileList="fileList2" multiple :maxCount="1" @afterRead="afterRead2" width="100" height="100" accept="video"
                   uploadText="上传视频" uploadIcon="play-right-fill" maxSize="10485760" @oversize="maxVideo"
                   @delete="deleteVideo"></uv-upload>
      </view>
    </view>

    <view class="form">
      <view class="form-item" style="border-bottom: 1px solid #eee;padding-bottom:10rpx;">
        <view class="lable" style="color:#000;">个人信息</view>
        <view style="color:#000;font-size:28rpx;line-height:40rpx;margin-top:10rpx;">
          为了尽快协助您解决诉求建议，请您根据《网络安全法》要求如实填写以下信息。您填写的联系方式仅供工作人员及留言办理单位反馈办理结果，他人无权浏览。关于隐私保护的具体条款可参阅：个人-服务协议-隐私保护。
        </view>
      </view>
      <view class="form-item uni-row" style="border-bottom: 1px solid #eee;padding:30rpx 0;">
        <view class="lable">电话：</view>
        <view style="color:#000;font-size:32rpx;margin-left:20rpx;">{{ userToken.getPhone }}</view>
      </view>

      <view class="form-item" style="padding:30rpx 0;border-bottom: 1px solid #eee;padding-bottom:10rpx;">
        <view class="lable">是否向有关办理机构提供手机号码</view>
        <view style="color:#555;margin-top:10rpx;">
          <uv-radio-group v-model="postData.is_zhanshi" size="24" labelSize="16">
            <uv-radio :customStyle="{margin: '8px'}" v-for="(item, index) in radio" :key="index"
                      :label="item.name" :name="item.value">
            </uv-radio>
          </uv-radio-group>
        </view>
      </view>

      <view class="form-item"
            style="padding:30rpx 0;padding-bottom:5rpx;border-bottom: 1px solid #eee;position: relative">
        <view class="lable">事发地</view>
        <uv-input placeholder="请输入事发地，或点击右侧定位" border="none" v-model="postData.address"
                  :customStyle="{padding:'0 60rpx 10rpx 0',margin:'20rpx 0 0 0'}"
                  :textStyle="{color:'#000',fontSize:'30rpx'}" maxlength="40" fontSize="16"></uv-input>
        <view style="position: absolute;right:4rpx;bottom:10rpx;" @click="gpswchat">
          <uv-icon name="map-fill" size="24"></uv-icon>
        </view>
      </view>

      <view class="form-item" style="margin-top:40rpx;">
        <view class="lable">备注：</view>
        <uv-textarea :placeholder="contentplaceholderbz" border="bottom" v-model="postData.remark"
                     :count="true" :height="200" :customStyle="{padding:'0 0 10rpx 0',margin:'0'}"
                     :textStyle="{color:'#000',fontSize:'30rpx'}" maxlength="200"></uv-textarea>
      </view>


      <view class="next uni-row" style="margin:60rpx 0 60rpx 0;">
        <view style="flex:1;margin-right:10rpx">
          <uv-button type="primary" text="上一步" plain @click="back" size="large"></uv-button>
        </view>
        <view style="flex:1;">
          <uv-button type="primary" text="确认发布" @click="doPost" size="large"
                     :loading="loading"></uv-button>
        </view>
      </view>
    </view>


  </view>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  nextTick,
  onMounted,
  watch
} from 'vue'
import {
  useToken
} from "@/stores/userStores";
import config from '@/common/config'
import runseIcon from '@/static/icon/runse.png'

const ailoading = ref(true)
const loading = ref(false)
const radiovalue = ref(1);
const userToken = useToken();
const postStatus = ref(0)
const runse = ref(null)
const AIendText = ref('');
const requestTask = ref(null)
const stopRunse = () => {
  runse.value.close()
  requestTask.value.abort();
  requestTask.value = null;
}
const ab2hex = (buffer) => {
  let hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
  )
  return hexArr.join('');
}
const goAitext = () => {

  if (postData.content == '' || !postData.content || postData.content?.length < 20) {
    uni.showModal({
      title: '提示',
      content: '正文内容为空或字数太少',
      showCancel: false,
    })
    return;
  }
  runse.value.open()
  ailoading.value = true;
  AIendText.value = '';
  requestTask.value = uni.request({
    url: `https://wz.mala.cn/chrome.Seo/test`,
    method: 'POST',
    data: {
      content: postData.content
    },
    header: {
      'Content-Type': 'application/json',
    },
    enableChunked: true,
    responseType: 'text',
    success: (res) => {
      if (res.data.code == 500) {
        stopRunse();
        uni.showModal({
          title: '提示',
          content: '正文内容为空',
          showCancel: false,
        })
      } else {
        ailoading.value = false;
      }
    },
    fail: (err) => {

    }
  });
  // 建立连接成功
  requestTask.value.onHeadersReceived(function (res) {
    console.log('建立连接成功', res);
  });
  let buffer = '';
  requestTask.value.onChunkReceived(function (res) {
    const arrayBuffer = res.data;
    const uint8Array = new Uint8Array(arrayBuffer);
    let text = String.fromCharCode.apply(null, uint8Array);
    // 将 ArrayBuffer 转换为字符串
    const textChunk = decodeURIComponent(escape(text));
    buffer += textChunk;
    const messages = buffer.split('\n\n');
    buffer = messages.pop();

    messages.forEach(msg => {
      if (msg.startsWith('data: ')) {

        const dataStr = msg.substring(6); // 去掉 "data: "

        if (dataStr === '[DONE]') {
          requestTask.value.abort();
          requestTask.value = null;
          return;
        }
        try {
          const data = JSON.parse(dataStr);
          if (data) AIendText.value += data.trim();
        } catch (e) {

        }
      }
    });
  });
}
const decode = (data) => {
  const text = decodeUTF8(data);
  const lines = text.split('\n');
  let result = '';

  for (let line of lines) {
    if (line.startsWith('data: ')) {
      const jsonData = line.slice(6).trim();

      // 结束标识处理
      if (jsonData === '[DONE]') return result;

      // 清理控制字符（防止JSON解析失败）
      const cleanedData = jsonData.replace(/[\u0000-\u001F\u007F-\u009F]/g, '');

      try {
        const parsedData = JSON.parse(cleanedData);
        // 提取AI生成内容
        result += parsedData.choices[0].delta.content || '';
      } catch (e) {
        console.error('解析失败:', e);
      }
    }
  }
  return result;
}
const decodeUTF8 = (data) => {
  // 将二进制数据转为Uint8数组
  const uint8Array = new Uint8Array(data);

  // 传统方式转换字符串（兼容旧环境）
  let string = '';
  for (let i = 0; i < uint8Array.length; i++) {
    string += String.fromCharCode(uint8Array[i]);
  }

  // 双重解码处理特殊字符（如中文）
  return decodeURIComponent(escape(string));
}
const doAi = () => {
  postData.content = AIendText.value
  runse.value.close()
}
const maxVideo = () =>{
  uni.showModal({
    title: '提示',
    content: '视频不能超过10M',
    showCancel: false,
  })
}
const back = () => {
  uni.navigateBack({
    delta: 1
  })
}
onMounted(() => {
  doRequire()
})
const doRequire = () => {
  uni.requirePrivacyAuthorize({
    success: () => {

    },
    fail: () => {
      console.log('拒绝');
    }, // 用户拒绝授权
    complete: () => {
    }
  })
}
const radio = ref([{name: '公开', value: 1}, {name: '不公开', value: 2}])

const fileList1 = ref([])
const fileList2 = ref([])
const deletePic = (event) => {
  fileList1.value.splice(event.index, 1)
}
const deleteVideo = (event) => {
  fileList2.value.splice(event.index, 1)
}
import {
  postProps
} from "@/stores/post";

const postparms = postProps();

import {doPostThread} from '@/common/thread'

const doPost = () => {
  // loading.value = true
  //拼装其他参数
  let fieldPost = {
    type: postparms.postType,   //分类
    classify: postparms.postClassify2,  //领域
    lid: postparms.lid,
    lid2: postparms.dy1,
    lid3: postparms.dy2,
    imgList: fileList1.value.map(item => item.url),
    video:fileList2.value.map(item => item.videoId),
  }
  let data = {fieldPost, ...postData}
  //检查数据
  if(postData.title=='' || !postData.title){
    uni.showModal({
      title: '提示',
      content: '标题不能为空',
      showCancel: false,
    })
    return false;
  }
  //检查内容
  if(postData.content=='' || !postData.content){
    uni.showModal({
      title: '提示',
      content: '正文不能为空',
      showCancel: false,
    })
    return false;
  }

  console.log(postparms.postType)
  //检查分类
  if(postparms.postType=='-1'){
    uni.showModal({
      title: '提示',
      content: '类别为空，请返回上一级选择分类',
    })
    return false;
  }

  //检查领域
  if(postparms.postClassify2=='' || !postparms.postClassify2){
    uni.showModal({
      title: '提示',
      content: '领域为空，请返回上一级选择领域',
    })
    return false;
  }

  //检测领导
  if(postparms.lid=='' || !postparms.lid){
    uni.showModal({
      title: '提示',
      content: '请选择部门，请返回上一级选择',
    })
    return false;
  }

  //lid2
  if(postparms.lid=='' || !postparms.lid){
    uni.showModal({
      title: '提示',
      content: '请选择事发地，返回上一层选择',
    })
    return false;
  }

  //发布留言，这里用了新的接口，用于小程序独立，后续APP也可以用
  doPostThread(data).then(r=>{
      if(r.code==200){
        uni.reLaunch({
          url:'/pages/thread/poststatus?status=1'
        })
      }else{
        uni.showModal({
          title: '提示',
          content: r.message,
          showCancel: false,
        })
      }
  })
  // uni.reLaunch({
  //   url:'/pages/thread/poststatus?status=1'
  // })
}
const postData = reactive({
  title: '',
  content: '',
  address: '',
  remark: '',
  is_zhanshi: 1
})
const gpswchat = () => {
  uni.chooseLocation({
    success: (res) => {
      postData.address = res.address;
    },
    fail: (res) => {
      console.log(res)
      // 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息

    }
  });
}
const uploadFilePromiseVideo= (file) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: config.baseUrl + '/wechatApi.Upload/create',
      filePath: file.url,
      name: 'file',
      formData: {
        'type': 'video',
        'info':JSON.stringify(file)
      },
      header: {
        Authorization: 'Bearer ' + userToken.token
      },
      success: (result) => {
        let res = JSON.parse(result.data)
        if (res.code == 200) {
          resolve(res.data)
        } else {
          reject(res.msg)
        }
      }
    })
  })
}
const uploadFilePromise = (file) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: config.baseUrl + '/wechatApi.Upload/create',
      filePath: file,
      name: 'file',
      formData: {
        'type': 'image'
      },
      header: {
        Authorization: 'Bearer ' + userToken.token
      },
      success: (result) => {
        let res = JSON.parse(result.data)
        if (res.code == 200) {
          resolve(res.data)
        } else {
          reject(res.msg)
        }
      }
    })
  })
}
const afterRead2 = async (event) => {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file)
  let fileListLen = fileList2.value.length
  lists.map((item) => {
    fileList2.value.push({
      ...item,
      status: 'uploading',
      message: '上传中'
    })
  })
  for (let i = 0; i < lists.length; i++) {
    console.log(lists[i])
    const result = await uploadFilePromiseVideo(lists[i])
    let item = fileList2.value[fileListLen]
    fileList2.value.splice(fileListLen, 1, Object.assign(item, {
      status: 'success',
      message: '',
      thumb: result.cover,
      url: result.src,
      videoId:result.videoId
    }))
    fileListLen++
  }
}
const afterRead = async (event) => {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file)
  let fileListLen = fileList1.value.length
  lists.map((item) => {
    fileList1.value.push({
      ...item,
      status: 'uploading',
      message: '上传中'
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url)
    let item = fileList1.value[fileListLen]
    fileList1.value.splice(fileListLen, 1, Object.assign(item, {
      status: 'success',
      message: '',
      url: result
    }))
    fileListLen++
  }
}
const contentplaceholder = "1.正文描述尽量简明扼要，避免添加过多的修饰词，最多输入1000字。\r\n2.个人或他人隐私请不要直接写在正文里，如有需要请写入下方辅助信息--备注栏中。\r\n3.所有违反本平台规范，负责，协议的留言均不会被采纳"
const contentplaceholderbz = "1.如果还有其他涉及到姓名、电话、身份证号码、详细地址等不便公开发布的信息，请填写此处。\r\n2.此处填写的信息不会公开显示在页面上，仅供麻辣社区工作人员及留言办理单位沟通您反映的问题，反馈办理结果，他人无权浏览。\r\n3.不超过200字。"
</script>


<style scoped lang="scss">
.runse-popup {
  padding: 48rpx;
  box-sizing: border-box;
  overflow: hidden;
  width: 560rpx;
  background: linear-gradient(180deg, #e5edff 0%, #ffffff 100%);
  border-radius: 24rpx;

  &__header {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 52rpx;
    font-size: 36rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 550;
    color: #1a1a1a;
    line-height: 52rpx;
    margin-bottom: 48rpx;
  }
}

.Aitext {
  position: absolute;
  bottom: 15rpx;
  right: 0;
  background: #eee;
  color: #3a48fb;
  font-size: 24rpx;
  border-radius: 30rpx;
  align-items: center;
  align-content: center;
  display: flex;
  padding: 8rpx 15rpx;

  svg {
    margin-right: 4rpx;
  }
}

.postForm {
  view {
    font-size: 28rpx;
  }

  .item {
    margin: 8rpx 0;

    .title {
      color: #000;
    }
  }
}

.form {
  padding: 20rpx 30rpx;
  margin-top: 30rpx;
  background: #fff;

}
</style>
